// scrollbar.js
import { nextTick } from 'vue'

const vScrollbar = {
    mounted(el, binding) {
        if (binding.value?.disabledAuto) {
            el.style.overflow = 'hidden'
        } else {
            // 确保元素可以滚动
            el.style.overflow = 'auto'
            el.style.scrollbarWidth = 'none' // Firefox
            el.style.msOverflowStyle = 'none' // IE
            el.style.webkitScrollbar = 'none' // Chrome/Safari
        }

        // 创建包裹容器
        const wrapper = document.createElement('div')
        wrapper.style.position = 'relative'
        wrapper.style.width = '100%'
        wrapper.style.height = binding.value?.height || '100%'

        // 将元素移动到包裹容器中
        el.parentNode.insertBefore(wrapper, el)
        wrapper.appendChild(el)

        // 创建自定义滚动条容器（放在包裹容器内，元素旁边）
        const scrollbar = document.createElement('div')
        scrollbar.className = 'custom-scrollbar'
        scrollbar.style.position = 'absolute'
        scrollbar.style.top = '0'
        scrollbar.style.right = '0'
        scrollbar.style.width = '12px'
        scrollbar.style.height = '100%'
        scrollbar.style.backgroundColor = 'transparent'
        scrollbar.style.borderRadius = '6px'
        scrollbar.style.transition = 'background-color 0.2s'
        scrollbar.style.zIndex = '9999'
        scrollbar.style.display = 'none'
        scrollbar.style.pointerEvents = 'none' // 允许穿透点击

        // 创建滚动条滑块
        const thumb = document.createElement('div')
        thumb.className = 'custom-scrollbar-thumb'
        thumb.style.position = 'absolute'
        thumb.style.right = '0'
        thumb.style.width = '12px'
        thumb.style.backgroundColor = binding.value?.color || '#ac6f22'
        thumb.style.borderRadius = '6px'
        thumb.style.cursor = 'pointer'
        thumb.style.opacity = '0.7'
        thumb.style.transition = 'opacity 0.2s, height 0.2s'
        thumb.style.pointerEvents = 'auto' // 允许拖动

        scrollbar.appendChild(thumb)
        wrapper.appendChild(scrollbar)

        // 保存相关元素和状态
        el._scrollWrapper = wrapper
        el._scrollbar = scrollbar
        el._thumb = thumb
        el._isDragging = false
        el._startY = 0
        el._startScrollTop = 0

        // 计算并更新滚动条滑块位置和大小
        const updateThumb = () => {
            const { scrollHeight, clientHeight, scrollTop } = el

            if (scrollHeight <= clientHeight) {
                scrollbar.style.display = 'none'
                return
            }

            const thumbHeight = Math.max((clientHeight / scrollHeight) * clientHeight, 20)
            const thumbTop = (scrollTop / scrollHeight) * clientHeight

            console.log(thumbTop)

            thumb.style.height = `${thumbHeight}px`
            thumb.style.top = `${thumbTop}px`
        }

        // 初始化更新
        updateThumb()

        // 监听滚动事件
        el.addEventListener('scroll', () => {
            if (!el._isDragging) {
                updateThumb()
            }
        })

        // 监听鼠标进入/离开
        wrapper.addEventListener('mouseenter', () => {
            scrollbar.style.display = 'block'
            scrollbar.style.backgroundColor = 'rgba(0, 0, 0, 0.1)'
            thumb.style.opacity = '0.7'
        })

        wrapper.addEventListener('mouseleave', () => {
            if (!el._isDragging) {
                scrollbar.style.display = 'none'
                scrollbar.style.backgroundColor = 'transparent'
                thumb.style.opacity = '0'
            }
        })

        // 鼠标按下事件
        thumb.addEventListener('mousedown', (e) => {
            el._isDragging = true
            el._startY = e.clientY
            el._startScrollTop = el.scrollTop

            document.addEventListener('mousemove', handleMouseMove)
            document.addEventListener('mouseup', handleMouseUp)

            e.preventDefault()
            e.stopPropagation()
        })

        // 鼠标移动事件
        const handleMouseMove = (e) => {
            if (!el._isDragging) return

            const deltaY = e.clientY - el._startY
            const scrollRatio = el.scrollHeight / el.clientHeight
            el.scrollTop = el._startScrollTop + deltaY * scrollRatio

            updateThumb()
        }

        // 鼠标释放事件
        const handleMouseUp = () => {
            el._isDragging = false
            document.removeEventListener('mousemove', handleMouseMove)
            document.removeEventListener('mouseup', handleMouseUp)

            // 如果鼠标不在元素内，隐藏滚动条
            if (!wrapper.matches(':hover')) {
                scrollbar.style.display = 'none'
                scrollbar.style.backgroundColor = 'transparent'
                thumb.style.opacity = '0'
            }

            updateThumb()
        }

        // 监听窗口大小变化
        const resizeObserver = new ResizeObserver(() => {
            updateThumb()
        })
        resizeObserver.observe(el)

        // 保存观察器以便卸载时清除
        el._resizeObserver = resizeObserver

        // 点击滚动条区域跳转
        scrollbar.addEventListener('click', (e) => {
            if (e.target === scrollbar) {
                const rect = scrollbar.getBoundingClientRect()
                const ratio = (e.clientY - rect.top) / rect.height
                el.scrollTop = ratio * (el.scrollHeight - el.clientHeight)
            }
        })
    },

    updated(el) {
        nextTick(() => {
            if (el._scrollbar) {
                const updateThumb = () => {
                    const { scrollHeight, clientHeight, scrollTop } = el

                    if (scrollHeight <= clientHeight) {
                        el._scrollbar.style.display = 'none'
                        return
                    }

                    const thumbHeight = Math.max((clientHeight / scrollHeight) * clientHeight, 20)
                    const thumbTop = (scrollTop / scrollHeight) * clientHeight

                    el._thumb.style.height = `${thumbHeight}px`
                    el._thumb.style.top = `${thumbTop}px`
                }

                updateThumb()
            }
        })
    },

    unmounted(el) {
        // 清理事件监听器和观察器
        if (el._resizeObserver) {
            el._resizeObserver.disconnect()
        }

        if (el._scrollWrapper && el._scrollWrapper.parentNode) {
            // 将元素移回原处
            el._scrollWrapper.parentNode.insertBefore(el, el._scrollWrapper)
            el._scrollWrapper.parentNode.removeChild(el._scrollWrapper)
        }
    }
}

export default vScrollbar